package com.qianfeng.smartdevice.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartdevice.pojo.Humiture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
public class HumitureWebSocketHandler extends MyBaseWebSocketHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ApplicationContext context;

    @Override
    public boolean isNeedUpdateStatus() {
        return true;
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String data = message.getPayload();//获取设备发送过来的数据

        try {
            Humiture humiture = objectMapper.readValue(data, Humiture.class);//解析数据
            String id = (String) session.getAttributes().get("name");
            humiture.setDeviceUUID(id);//设置id
            humiture.setTemperature((humiture.getTemperature()-32)/1.8);//温度默认是华氏,转换为摄氏
            context.publishEvent(humiture);
        }catch (Exception e){
           e.printStackTrace();
        }
        super.handleTextMessage(session,message);
    }
}
